import { Component, forwardRef } from '@angular/core';

import { EmojiProvider } from '../../providers/emoji/emoji';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

/**
 * 实现接口ControlValueAccessor
 * 
 * @export
 * @class EmojipickerComponent
 * @implements {ControlValueAccessor}
 */
//实现 EmojipickerComponent 的 providers
export const EMOJI_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => EmojipickerComponent),
  multi: true
}

@Component({
  selector: 'emojipicker',
  templateUrl: 'emojipicker.html',
  providers: [EMOJI_ACCESSOR]
})

export class EmojipickerComponent implements ControlValueAccessor {
  emojiArray = [];
  content: string;
  onChanged: Function;
  OnTouched: Function;

  constructor(emojiProvider: EmojiProvider) {
    this.emojiArray = emojiProvider.getEmojis();
  }
  writeValue(obj: any): void {
    this.content = obj;
  }
  registerOnChange(fn: any): void {
    this.onChanged = fn;
    this.setValue(this.content);
  }
  registerOnTouched(fn: any): void {
    this.OnTouched = fn;
  }
   //再次处理新的内容赋值以及函数的绑定
  setValue(val: any): any {
    this.content += val;
    if (this.content) {
      this.onChanged(this.content);
    }
  }
}
